package org.piwicode.bywordofmouth.net;

import com.google.common.base.Preconditions;
import com.google.inject.internal.ImmutableMap;
import com.google.inject.internal.ImmutableMap.Builder;
import com.google.inject.internal.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import javax.annotation.concurrent.ThreadSafe;

/**
 *
 * @author pierre
 */
@ThreadSafe
class Service {

    private final Map<String, Method> methodsByName;
    private final Object implementation;

    Service(Object implementation) {
        this.implementation = Preconditions.checkNotNull(implementation);
        final Builder<String, Method> bldr = ImmutableMap.builder();
        for (Method m : implementation.getClass().getMethods()) {
            if (m.getDeclaringClass() != Object.class)
                bldr.put(m.getName(), m);
        }
        methodsByName = bldr.build();
    }

    Object call(String methodName, @Nullable Object args[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        return methodsByName.get(methodName).invoke(implementation, args);
    }
}
